<template>
  <el-dialog
    :model-value="editDialogVisible"
    title="驾校修改"
    width="700"
    :before-close="resetForm"
    :close-on-click-modal="false"
  >
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="驾校名称" prop="storeName">
        <el-input v-model="ruleForm.storeName" placeholder="请输入驾校名称" />
      </el-form-item>
      <el-form-item label="驾校LOGO">
        <el-input v-model="ruleForm.storeLogo" style="display: none"></el-input>

        <el-upload
          class="avatar-uploader"
          :action="server"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-image v-if="storeLogo" :src="storeLogo" class="avatar" fit="contain"></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"
            ><el-icon><Plus /></el-icon
          ></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="所属区域" prop="area">
        <el-cascader
          ref="addressInfo"
          v-model="ruleForm.area"
          :options="addressOptions"
          @change="handleChange"
          :props="addressProps"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="驾校简介" prop="storeDesc">
        <el-input v-model="ruleForm.storeDesc" type="textarea" :autosize="{ minRows: 8 }" />
      </el-form-item>
      <el-form-item label="所属套餐" prop="thaliId">
        <el-select v-model="ruleForm.thaliId" placeholder="请选择">
          <el-option
            v-for="item in menuOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="editLoading" @click="submitForm(ruleFormRef)"
          >确认</el-button
        >
        <el-button @click="resetForm">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import { useUserStore } from '@/store/modules/user'
  import { getAddressInfo, getThaliData, editDrivingSchoolInfo } from '@/api/ApiList'

  const props = defineProps({
    editDialogVisible: {
      type: Boolean
    },
    editInfo: {
      type: Object,
      default: () => {
        id: ''
      }
    }
  })

  const emit = defineEmits(['closeDialog'])

  const userStore = useUserStore()
  const addressOptions = ref([])
  const addressProps = ref({ value: 'code', label: 'name', children: 'children' })
  let server = `${import.meta.env.VITE_API_URL}files`
  let { accessToken } = userStore
  const headers = { Authorization: 'Bearer ' + accessToken }
  const storeLogo = ref('')
  const addressInfo = ref()
  const editLoading = ref(false)

  const userInfo = computed(() => userStore.getUserInfo)

  interface RuleForm {
    storeName: string
    storeLogo: string
    provinceCode: string
    provinceName: string
    cityCode: string
    cityName: string
    storeDesc: string
    thaliId: string
    areaCode: string
    areaName: string
    area?: any[]
  }

  interface menuType {
    label: string
    value: string
  }

  let menuOptions = ref<menuType[]>([])

  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive<RuleForm>({
    storeName: '',
    storeLogo: '',
    provinceCode: '',
    provinceName: '',
    cityCode: '',
    cityName: '',
    areaCode: '',
    areaName: '',
    storeDesc: '',
    thaliId: ''
  })

  const handleChange = (val: any) => {
    const areaText = addressInfo.value.presentText
    const addressSplit = areaText.split('/')
    ruleForm.provinceCode = val[0]
    ruleForm.provinceName = addressSplit[0]
    ruleForm.cityCode = val[1]
    ruleForm.cityName = addressSplit[1]
    ruleForm.areaCode = val[2]
    ruleForm.areaName = addressSplit[2]
  }

  const rules = reactive<FormRules<RuleForm>>({
    storeName: [{ required: true, message: 'Please input Activity name', trigger: 'blur' }],
    storeDesc: [
      {
        required: true,
        message: 'Please input',
        trigger: 'blur'
      }
    ],
    thaliId: [
      {
        required: true,
        message: 'Please input',
        trigger: 'change'
      }
    ]
  })

  const handleAvatarSuccess = (file: any) => {
    storeLogo.value = file.data.url
    ruleForm.storeLogo = file.data.url
  }
  //上传限制大小格式等
  const beforeAvatarUpload = (file: any) => {
    const isLt2M = file.size / 10240 / 10240 < 2
    if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
      ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('上传头像图片大小不能超过 20MB!!')
      return false
    }
  }

  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        let obj: any = { ...ruleForm }
        obj.userId = userInfo.value.id
        delete obj.area
        edit(obj)
      } else {
      }
    })
  }

  async function edit(data: any) {
    try {
      const res = await editDrivingSchoolInfo(data, props.editInfo.id)
      if (res.code === '00000') {
        ElMessage.success('修改成功')
        emit('closeDialog', true)
      }
    } catch (e) {
    } finally {
    }
  }

  const resetForm = () => {
    emit('closeDialog')
  }

  //请求地址级联接口
  const getAddressListData = async () => {
    const res = await getAddressInfo()
    if (res.code === '00000') {
      addressOptions.value = res.data
    }
  }

  const getThaliList = async () => {
    const res = await getThaliData()
    if (res.code === '00000') {
      menuOptions.value = res.data
    }
  }

  onMounted(() => {
    let allKey = Object.keys(ruleForm)
    for (const key in props.editInfo) {
      if (allKey.includes(key)) {
        // ruleForm[key] = props.editInfo[key]
        ruleForm[key as keyof typeof ruleForm] = props.editInfo[key]
      }
    }

    storeLogo.value = ruleForm.storeLogo
    ruleForm.area = [ruleForm.provinceCode, ruleForm.cityCode, ruleForm.areaCode]

    getAddressListData()
    getThaliList()
  })
</script>

<style scoped lang="scss">
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
